/**
 * Copyright (c) 2015-2017, Javen Zhou  (javen205@126.com).
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */

package com.javen.weixin.service;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javen.weixin.common.model.User;
import com.javen.weixin.kit.URLCodeKit;
import com.jfinal.kit.Kv;
import com.jfinal.kit.StrKit;
import com.jfinal.log.Log;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.weixin.sdk.api.ApiResult;

/**
 * 个性化自定义菜单
 * 
 * @author Javen 2017年6月24日
 */
public class WxUserService {
	static Log log = Log.getLog(WxUserService.class);
	public static final WxUserService me = new WxUserService();
	private final User dao = new User().dao();
	
	public User getByOpenId(String appId,String openId){
		Kv para = Kv.by("app_id",appId).set("open_id",openId);
		SqlPara sqlPara = dao.getSqlPara("wxuser.getByAppIdAndOpenId", para);
		return dao.findFirst(sqlPara);
	}
	
	public User toSave(String appId,ApiResult apiResult){
		JSONObject jsonObject=JSON.parseObject(apiResult.getJson());
		String openId = jsonObject.getString("openid");
		String nickName = jsonObject.getString("nickname");
		nickName = URLCodeKit.encode(nickName);
		int sex = jsonObject.getIntValue("sex");
		String city = jsonObject.getString("city");//城市
		String province=jsonObject.getString("province");//省份
		String country=jsonObject.getString("country");//国家
		String headimgurl=jsonObject.getString("headimgurl");
		String unionid=jsonObject.getString("unionid");
		
		return save(appId, openId, nickName, unionid, headimgurl, country, city, province, sex);
	}

	public User save(String appId,String openId, String nickName, String unionid, String headimgurl, String country, String city,
			String province, int sex) {

//		log.error("appId:"+appId+" openId:" + openId + " nickName:" + nickName + " unionid:" + unionid + " headimgurl:" + headimgurl
//				+ " country:" + country + " city:" + city + " province:" + province + " sex:" + sex);

		/**
		 * 
		 * 1、判断openId 是否存在
		 * 
		 * 如果存在就update
		 * 
		 * 如果不存在就保存
		 * 
		 */
		User user = getByOpenId(appId,openId);
		if (user != null) {
			user.setNickName(nickName);
			user.setUnionid(unionid);
			user.setHeadimgurl(headimgurl);
			user.setCountry(country);
			user.setCity(city);
			user.setProvince(province);
			user.setSex(sex);
			user.setUpdateTime(new Date());
			boolean update = user.update();
			if (update) {
				return user;
			}
		} else {
			if (StrKit.notBlank(openId)) {
				User me = new User();
				me.setAppId(appId);
				me.setOpenId(openId);
				me.setNickName(nickName);
				me.setUnionid(unionid);
				me.setHeadimgurl(headimgurl);
				me.setCountry(country);
				me.setCity(city);
				me.setProvince(province);
				me.setSex(sex);
				me.setUpdateTime(new Date());
				me.setCreateTime(new Date());
				boolean save = me.save();
				if (save) {
					return me;
				}
				
			}
		}
		return null;
	}
}
